const express = require('express');
const mysql = require('mysql2');

const app = express();

const pool = mysql.createPool({
    host: '47.109.42.76',
    user: 'miaolegemiao',
    password: 'Miaolegemiao@123',
    database: 'miaolegemiao',
    waitForConnections: true,
    connectionLimit: 100,
    queueLimit: 0
});
const cors = require('cors');

// 在路由之前添加以下代码
app.use(cors());
// 解析请求体中的JSON数据，并将其转换为JavaScript对象，使得req.body能够访问到请求体中的数据。
app.use(express.json());

app.post('/api/data', (req, res) => {
    pool.getConnection((err, connection) => {
        if (err) {
            res.status(500).json({ error: 'Internal Server Error' });
            return
        }
        connection.query('insert into `rank`(username, end_time, time, numbers, difficulty_factor, points) values("' +
            req.body.username + '","' + req.body.endTime + '","' + req.body.seconds + '","' + req.body.total + '","' 
            + req.body.difficultyFactor + '","' + req.body.points + '")'
            , (error, results, fields) => {
                connection.release();

                if (error) {
                    console.error(error);
                    res.status(500).json({ error: 'Internal Server Error' });
                    return
                }
                res.json(results);
            });
    });
});

app.get('/api/rank', (req, res) => {
    pool.getConnection((err, connection) => {
        if (err) {
            console.error(err);
            res.status(500).json({ error: 'Internal Server Error' });
            return
        }
        connection.query('select * from `rank` where DATE(end_time) = "'+ req.query.date +'" order by difficulty_factor, time, points limit 10', (error, results, fields) => {
                connection.release();

                if (error) {
                    console.error(error);
                    res.status(500).json({ error: 'Internal Server Error' });
                    return
                }
                res.json(results);
            });
    });
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});
